//
//  ApplicantViewController.m
//  PlayCatchGame
//
//  Created by 流言 on 2018/2/27.
//  Copyright © 2018年 清正. All rights reserved.
//

#import "ApplicantViewController.h"

#import "AppHeader.h"
#import "ExchangeCell.h"
#import "AddressView.h"

#import "AdderssManageVC.h"

#import "PrizeModel.h"
#import "AddressModel.h"

@interface ApplicantViewController () <UITableViewDelegate, UITableViewDataSource>

@property (assign, nonatomic) NSInteger venosaCount;
@property (weak, nonatomic) IBOutlet UILabel *moneyCountLabel;
@property (weak, nonatomic) IBOutlet UIButton *sendButton;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
// 默认地址
@property (nonatomic, strong) AddressModel *addressModel;
// 请求到的prize的数据
@property (nonatomic, strong) NSMutableArray<GoodsModel *> *goodsList;

@end

@implementation ApplicantViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.goodsList = [NSMutableArray array];
    [self _requestNetwork];
    [self _getPrizeInfo];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

}


#pragma mark - Request Network
- (void)_requestNetwork {
    [HttpUrl GET:@"address/selectDefaultAddress" dict:nil hud:self.view isShow:YES WithSuccessBlock:^(id data) {
        if (BB_isSuccess) {
            self.addressModel = [AddressModel mj_objectWithKeyValues:data[@"data"]];
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade
             ];
        } else {
            ShowAlertTitle(@"获取地址失败");
        }
    }];
}

- (void)_getPrizeInfo {
    
    //    NSMutableArray *idList = [NSMutableArray array];
    NSMutableString *idString = @"".mutableCopy;
    
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        PrizeModel *model = self.dataArray[i];
        [idString appendString:[NSString stringWithFormat:@"%ld", model.id]];
        if (i == self.dataArray.count - 1) {
            continue;
        }
        [idString appendString:@","];
    }
//
//    [HttpUrl uploadForm:@"myPrize/applyExpress" withDic:@{@"ids": idString} hud:self.view vc:self isShow:YES WithSuccessBlock:^(id data) {
//        if (BB_isSuccess) {
//            for (NSDictionary *dic in data[@"data"]) {
//                GoodsModel *goodsModel = [GoodsModel mj_objectWithKeyValues:dic];
//                [self.goodsList addObject:goodsModel];
//                self.venosaCount += goodsModel.expressMoney;
//            }
//            dispatch_async(dispatch_get_main_queue(), ^{
//                self.moneyCountLabel.text = [NSString stringWithFormat:@"%ld金豆", self.venosaCount];
//            });
//            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
//        } else {
//            ShowAlertTitle(data[@"msg"]);
//        }
//    } withFailureBlock:^(NSError *error) {
//
//    }];
    
        [HttpUrl GET:@"myPrize/applyExpress"dict:@{@"ids": idString} hud:self.view isShow:YES WithSuccessBlock:^(id data) {
            if (BB_isSuccess) {
                for (NSDictionary *dic in data[@"data"][@"goods"]) {
                    GoodsModel *goodsModel = [GoodsModel mj_objectWithKeyValues:dic];
                    [self.goodsList addObject:goodsModel];
                }
                self.venosaCount = [data[@"data"][@"expressMoney"] integerValue];
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.moneyCountLabel.text = [NSString stringWithFormat:@"%ld金豆", self.venosaCount];
                });
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
            } else {
                ShowAlertTitle(data[@"msg"]);
            }
        }];
    
}


- (AddressModel *)addressModel {
    if (!_addressModel) {
        _addressModel = [[AddressModel alloc] init];
    }
    return _addressModel;
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section ==0) {
        return 1;
    } else {
        return self.goodsList.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.section ==0) {
//        return 55.0+[@"浙江省杭州市拱墅区北软附近xxxxxxxxxxxx号x层xxx楼" stringOfFondSize:16 aWidth:KScreenWidth-58].height;
        return 55.0+[self.addressModel.completeAdress stringOfFondSize:16 aWidth:KScreenWidth-58].height;
    } else {
        return 100;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section ==0) {
        return 10;
    } else {
        return 35;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section ==0) {
        return 0.1;
    } else {
        return 44;
    }
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 10)];
    headerView.backgroundColor =tableView.backgroundColor;
    if (section ==1) {
        headerView.frame =CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 35);
        
        UILabel *titleLabel =[[UILabel alloc] initWithFrame:CGRectMake(10, 0, KScreenWidth-20, CGRectGetHeight(headerView.frame))];
        titleLabel.textAlignment =NSTextAlignmentLeft;
        titleLabel.textColor =[UIColor grayColor];
        titleLabel.text =@"订单信息";
        [headerView addSubview:titleLabel];
    }
    return headerView;
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 0.1)];
    footerView.backgroundColor =[UIColor whiteColor];
    
    if (section ==1) {
        footerView.frame =CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 44);
        
        UIView *lineView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 1)];
        lineView.backgroundColor =tableView.separatorColor;
        [footerView addSubview:lineView];
        
        UILabel *titleLabel =[[UILabel alloc] initWithFrame:CGRectMake(10, 0, (KScreenWidth-20)/2.0, CGRectGetHeight(footerView.frame))];
        titleLabel.text =@"运费";
        [footerView addSubview:titleLabel];
        
        UILabel *contentLabel =[[UILabel alloc] initWithFrame:CGRectMake(10+(KScreenWidth-20)/2.0, 0, (KScreenWidth-20)/2.0, CGRectGetHeight(footerView.frame))];
        contentLabel.textAlignment =NSTextAlignmentRight;
        contentLabel.textColor =APP_DEFAULT_COLOUR;
        contentLabel.text =[NSString stringWithFormat:@"+%ld金豆", self.venosaCount];
        [footerView addSubview:contentLabel];
    }
    
    return footerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section ==0) {
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"UITabelViewCell"];
        AddressView *adderss =[cell.contentView viewWithTag:203];
        if (!cell) {
            cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITabelViewCell"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            
            adderss =[AddressView loadNib:@"AddressView" frame:CGRectZero];
            adderss.tag =203;
            [cell.contentView addSubview:adderss];
            
            [adderss mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(cell.contentView.mas_top).offset(0);
                make.left.mas_equalTo(cell.contentView.mas_left).offset(0);
                make.right.mas_equalTo(cell.contentView.mas_right).offset(0);
                make.bottom.mas_equalTo(cell.contentView.mas_bottom).offset(0);
            }];
        }
        adderss.phoneLabel.text = [NSString stringWithFormat:@"%@", self.addressModel.recipientsPhone];
        adderss.nameLabel.text = [NSString stringWithFormat:@"%@", self.addressModel.recipients];
        adderss.contentLabel.text = self.addressModel.completeAdress;
        return cell;
    } else {
        ExchangeCell *cell =[tableView dequeueReusableCellWithIdentifier:@"ExchangeCell"];
        if (!cell) {
            cell =[ExchangeCell findCellWithIdentifier:@"ExchangeCell"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
        }
        GoodsModel *model = self.goodsList[indexPath.row];
        cell.nameLabel.text = [NSString stringWithFormat:@"%@", model.goodsTitle];
        cell.timeLabel.text = [NSString stringWithFormat:@"%@", model.gmtDatetime.length > 16 ? [model.gmtDatetime substringToIndex:16] : model.gmtDatetime];
        [cell.image0View sd_setImageWithURL:[NSURL URLWithString:model.coverUrl] placeholderImage:[UIImage imageNamed:@"quanxi-dianji"]];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section ==0 && indexPath.row ==0) {
        AdderssManageVC *addressVC =[[AdderssManageVC alloc] init];
        addressVC.title =@"收货地址";
        addressVC.chooseBlock = ^(AddressModel *model) {
            self.addressModel = model;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            });
            
        };
        [self.navigationController pushViewController:addressVC animated:YES];
    }
}

- (IBAction)submitButtonClick:(UIButton *)sender {
    NSMutableString *idString = @"".mutableCopy;
    
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        PrizeModel *model = self.dataArray[i];
        [idString appendString:[NSString stringWithFormat:@"%ld", model.id]];
        if (i == self.dataArray.count - 1) {
            continue;
        }
        [idString appendString:@","];
    }
    
    [HttpUrl GET:@"myPrize/conmfirmExpress"dict:@{@"ids":idString, @"addressId" : @(self.addressModel.id)} hud:self.view isShow:YES WithSuccessBlock:^(id data) {
        if (BB_isSuccess) {
            
            jxt_showAlertOneButton(@"提示", @"提交成功", @"确定", ^(NSInteger buttonIndex) {
                [self.delegate prizeSubmitResult:YES];
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        } else {
            ShowAlertTitle(data[@"msg"]);
        }
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
